package com.liang.gulimall.cart.controller;

import com.liang.gulimall.cart.service.CartService;
import com.liang.gulimall.cart.vo.Cart;
import com.liang.gulimall.cart.vo.CartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.concurrent.ExecutionException;

@Controller
public class CartController {
    @Autowired
    CartService cartService;
    /**
     * 到购物车页
     * @return
     */
    @GetMapping("/cart.html")
    public String cartListPage(Model model) throws ExecutionException, InterruptedException {
        //UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        Cart cart=cartService.getCartInfo();
        model.addAttribute("cart",cart);
        return "cartList";
    }

    /**
     * 一直刷新成功页面，会不断发请求向购物车添加商品，可以再写个视图映射方法重定向到成功页，
     * RedirectAttributes 重定向携带数据
     * @param skuId
     * @param num
     * @param
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @GetMapping("/addToCart")
    public String addToCart(@RequestParam("skuId") Long skuId, @RequestParam("num") Integer num,
                            RedirectAttributes redirectAttributes) throws ExecutionException, InterruptedException {
        cartService.addToCart(skuId,num);
        redirectAttributes.addAttribute("skuId",skuId);
        return "redirect:http://cart.gulimall.com/toSuccessPage.html";

    }
    @GetMapping("/toSuccessPage.html")
    public String toSuccessPage(@RequestParam("skuId") Long skuId,Model model){
        CartItem cartItem= cartService.getCartItem(skuId);

        model.addAttribute("item",cartItem);
        return "success";
    }
    @GetMapping("/checkItem")
    public String setCheckItem(@RequestParam("skuId") Long skuId,@RequestParam("check") Integer check){
        cartService.checkItem(skuId,check);
        return "redirect:http://cart.gulimall.com/cart.html";
    }
    @GetMapping("/countItem")
    public String setCountItem(@RequestParam("skuId") Long skuId,@RequestParam("num") Integer count){
        cartService.setCountItem(skuId,count);
        return "redirect:http://cart.gulimall.com/cart.html";
    }
    @GetMapping("/deleteItem")
    public String deleteItem(@RequestParam("skuId") Long skuId){
        cartService.deleteItem(skuId);
        return "redirect:http://cart.gulimall.com/cart.html";
    }

    @ResponseBody
    @GetMapping("/userCartItem")
    public List<CartItem> getUserCheckedItem(){
        return cartService.getUserCheckedItem();
    }
}
